 /****************************************************************************
 **
 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
 ** Contact: Nokia Corporation (qt-info@nokia.com)
 **
 ** This file is part of the examples of the Qt Toolkit.
 **
 ** $QT_BEGIN_LICENSE:LGPL$
 ** Commercial Usage
 ** Licensees holding valid Qt Commercial licenses may use this file in
 ** accordance with the Qt Commercial License Agreement provided with the
 ** Software or, alternatively, in accordance with the terms contained in
 ** a written agreement between you and Nokia.
 **
 ** GNU Lesser General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU Lesser
 ** General Public License version 2.1 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU Lesser General Public License version 2.1 requirements
 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **
 ** In addition, as a special exception, Nokia gives you certain
 ** additional rights. These rights are described in the Nokia Qt LGPL
 ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
 ** package.
 **
 ** GNU General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU
 ** General Public License version 3.0 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.  Please review the following information to
 ** ensure the GNU General Public License version 3.0 requirements will be
 ** met: http://www.gnu.org/copyleft/gpl.html.
 **
 ** If you are unsure which license is appropriate for your use, please
 ** contact the sales department at http://www.qtsoftware.com/contact.
 ** $QT_END_LICENSE$
 **
 ****************************************************************************/

#include <QtGui>
#include <QtNetwork>

#include "HttpWindow.h"
#include "rf.h"

 HttpDownload::HttpDownload(QString *text, QObject *parent )
     : QObject(parent)
 {
     _DEBUG_
     target = text;

     http = new QHttp(this);

     connect(http, SIGNAL(requestFinished(int, bool)),
             this, SLOT(httpRequestFinished(int, bool)));
     connect(http, SIGNAL(dataReadProgress(int, int)),
             this, SLOT(updateDataReadProgress(int, int)));
     connect(http, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)),
             this, SLOT(readResponseHeader(const QHttpResponseHeader &)));
     connect(http, SIGNAL(authenticationRequired(const QString &, quint16, QAuthenticator *)),
             this, SLOT(slotAuthenticationRequired(const QString &, quint16, QAuthenticator *)));
 #ifndef QT_NO_OPENSSL
     connect(http, SIGNAL(sslErrors(const QList<QSslError> &)),
             this, SLOT(sslErrors(const QList<QSslError> &)));
 #endif
 }

 void HttpDownload::downloadFile()
 {
     _DEBUG_
     QUrl url("");
     url.setUrl( target->toLatin1() );
     QFileInfo fileInfo(url.path());
     QString fileName = fileInfo.fileName();
     _DEBUG_

     if (fileName.isEmpty())
         fileName = "index.html";
     _DEBUG_

     if (QFile::exists(fileName)) {
         /*if (QMessageBox::question(this, tr("HTTP"),
                                   tr("There already exists a file called %1 in "
                                      "the current directory. Overwrite?").arg(fileName),
                                   QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Cancel)
             == QMessageBox::Cancel)
             return;*/
         QFile::remove(fileName);
     }
     _DEBUG_

     file = new QFile(fileName);
     if (!file->open(QIODevice::WriteOnly)) {
         QMessageBox::information(0, tr("HTTP"),
                                  tr("Unable to save the file %1: %2.")
                                  .arg(fileName).arg(file->errorString()));
         delete file;
         file = 0;
         return;
     }
     _DEBUG_

     QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
     http->setHost(url.host(), mode, url.port() == -1 ? 0 : url.port());

     if (!url.userName().isEmpty())
         http->setUser(url.userName(), url.password());

     httpRequestAborted = false;
     QByteArray path = QUrl::toPercentEncoding(url.path(), "!$&'()*+,;=:@/");
     if (path.isEmpty())
         path = "/";
     httpGetId = http->get(path, file);
     qDebug() << "GetID: " << httpGetId;
     httpRequestFinished( httpGetId, false );
 }

 void HttpDownload::cancelDownload()
 {
     _DEBUG_
     httpRequestAborted = true;
     http->abort();     
 }

 void HttpDownload::httpRequestFinished(int requestId, bool error)
 {
     _DEBUG_
     if (requestId != httpGetId)
         return;
     if (httpRequestAborted) {
         if (file) {
             file->close();
             file->remove();
             delete file;
             file = 0;
         }


         return;
     }

     if (requestId != httpGetId)
         return;

     file->close();

     if (error) {
         file->remove();
         QMessageBox::information(0, tr("HTTP"),
                                  tr("Download failed: %1.")
                                  .arg(http->errorString()));
     } else {
         QString fileName = QFileInfo(QUrl(target->toLatin1()).path()).fileName();
     }
     delete file;
     file = 0;
 }

 void HttpDownload::readResponseHeader(const QHttpResponseHeader &responseHeader)
 {
     _DEBUG_
     qDebug() << "Response:" << responseHeader.statusCode();
     switch (responseHeader.statusCode()) {
     case 200:                   // Ok
     case 301:                   // Moved Permanently
     case 302:                   // Found
     case 303:                   // See Other
     case 307:                   // Temporary Redirect
         // these are not error conditions
         break;

     default:
         QMessageBox::information(0, tr("HTTP"),
                                  tr("Download failed: %1.")
                                  .arg(responseHeader.reasonPhrase()));
         httpRequestAborted = true;

         http->abort();
     }
 }

 void HttpDownload::updateDataReadProgress(int bytesRead, int totalBytes)
 {
     _DEBUG_
     if (httpRequestAborted)
         return;

     qDebug() << "Downloading" << bytesRead << "of" << totalBytes;
 }

 void HttpDownload::slotAuthenticationRequired(const QString &hostName, quint16, QAuthenticator *authenticator)
 {
     _DEBUG_
 }

 #ifndef QT_NO_OPENSSL
 void HttpDownload::sslErrors(const QList<QSslError> &errors)
 {
     _DEBUG_
     QString errorString;
     foreach (const QSslError &error, errors) {
         if (!errorString.isEmpty())
             errorString += ", ";
         errorString += error.errorString();
     }

     if (QMessageBox::warning(0, tr("HTTP Example"),
                              tr("One or more SSL errors has occurred: %1").arg(errorString),
                              QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) {
         http->ignoreSslErrors();
     }
 }
 #endif
